var TURN_START = 0;
var TURN_PLAY = 1;
var TURN_END = 2;

ExtGames.Game = function(config) {
  
  console.log('Creating Pack');
  this.pack = new ExtGames.Pack(config);
  
  if (!this.win) {
	  
	 console.log('Creating Window');
	  
    this.win = new ExtGames.MainWindow({
      game:       this
    });
  };
  
  this.round = 0;
  
  
  
};

ExtGames.Game.prototype = {
  
  inProgress: true,
  
  round: 0,
  
  turn: 0,
  
  didPlay: false,
  
  newGameClicked: function(config) {
    if (this.inProgress == true) {
	    Ext.Msg.confirm('Game in progress', "Are you sure?  You'll lose your current game", function(btn) {
	        if (btn == 'yes') {
	           var selectionWin = new ExtGames.GameSelectionWindow();
	           selectionWin.show();
	        };
	      });
	              
     }
     
  },
  
  newGame: function() {
    
  },
  
  /**
   * Sets up the Deck
   */
  createDecks: function() {
	  console.log('Creating Deck');
	  
    this.decks = [];
    for (var i = 0; i < this.getNumberOfDrawPiles(); i++) {
	    this.decks.push(new ExtGames.UnusedDeck({
	    	itemId: 'deck_' + i
	    }));
    }
    return this.decks;
    
  },
  
  createDiscardPiles: function() {
	  
    this.discardpiles = [];
    for (var i = 0; i < this.getNumberOfDiscardPiles(); i++) {
	    this.discardpiles.push(new ExtGames.DiscardPile({
	    	itemId: 'discardPile_'+i,
	    	listeners: {
	            'carddropped': {
	            	fn: this.dropCard,
	            	scope: this,
	            }
	          }
	    }));
    }
    return this.discardpiles;
    
  },
  
  createScorecard: function() {
	  console.log('Creating scorecard');
	  this.scorecard = new ExtGames.Scorecard({
			 title: 'Scorecard',
			 collapsed: true,
			 split: true,
			 width: 400,
			 collapsible: true,
			 region: 'east'
	  });  
	  
	  return this.scorecard;
  },
  

  
  
  populateHand: function() {
	  	  
	  var numCards = this.getNumberOfCardsToDeal();
	  	  	  
	  var num = util.getTurnIndex();
	  	  	  
	  for (var i = 0; i < numCards; i++) {
		  for (var j = 0; j < this.hands.length; j++) {
			  			  			  
			  var card = this.pack.getTopCard();
			  			  
			  if (num == 0) {
				  card.revealed = true;
			  }
		      			  
		      card.move(this.hands[num]);
		      		      
		      num++;
		      if (num >= this.hands.length) {
		    	  num = 0;
		      }
		  }
	  }
	  	  
	  this.hands[0].sortCards();
  },
  
  
  
  /**
   * Creates stacks components
   */
  createHands: function() {
	  
	 console.log('Creating Hand');
	  
	this.hands = [];
	  
	this.hands.push(new ExtGames.Hand({
		itemId: 'hand',
		type: 0,
		listeners: { 
            'carddropped': {
            	fn: this.dropCard,
            	scope: this,
            }
          }
 
        }));  
	
	
	var opp = util.getOpponents();
			
	for (var i = 0; i < opp.length; i++) {
		this.hands.push(new ExtGames.Hand({
			itemId: 'hand_'+opp[i].id,
			handName: opp[i].name,
			type: 1,
			listeners: {
	            'carddropped': {
	            	fn: this.dropCard,
	            	scope: this,
	            }
	          }
	 
	        }));  
	}
		
	console.log('Created '+this.hands.length+' hands');
	
	return this.hands;
	
  },
  
  createPlayareas: function() {
  	  this.playareas = [];
  },
  
  /**
   * Starts the game by opening the window
   */
  launch: function() {
    this.win.render();
    
    //this.pack.createCards({decks: 2});
  	//this.reformDeck();
  },
  
  dropCard: function(stack, card, e) {	  
	  
  },
  
  nextTurn: function() {
	  	  	  	  
	  if (util.isTurn()) {
		  this.turn = TURN_START;
	  }
	  	  
	  this.updateStatusTurn();
	  
	  var index = util.getTurnIndex();
	  this.hands[index].setTurn();
	  	  	  
	  index--;
	  if (index < 0) {
	  	index += util.getNumP();
	  }
	  
	  this.hands[index].removeTurn();
  },
  
  getScore: function() {
	  
  },
  
  endRound: function() {
	  console.log('Round ended. You Win.');
	  
	  util.submitScores(this.getScores());
	  
	  if (this.isGameEnd()) {
	  	//this.gameEnd();
	  }
	  else {
	  	this.pack.createCards({
	  		decks: NUM_DECKS
	  	});
	  	util.nextRound();
	  }
	  
  },
  
  gameEnd: function() {
  	  var winnerIds = getWinnerList(this.scorecard.getTotals());
  	  var winnerString = '';
  	  for (var i = 0; i < winnerIds.length; i++) {
  	  	 if (i > 0) {
  	  	 	winnerString += ' and ';
  	  	 }
  	  	 winnerString = util.getName(winnerIds[i]);
  	  }
  	  Ext.MessageBox.alert('And the winner is...', winnerString);
  },
  
  updateScores: function(scorecard) {
  	
	  this.scorecard.displayScores(scorecard);
	  
	  for (var i = 0; i < this.hands.length; i++) {
	  		this.hands[i].reveal();
	  }
	  
	  this.scorecard.expand(true);
	  
	  if (this.isGameEnd()) {
	  	this.gameEnd();
	  }
  },
  
  getPack: function() {
	  return this.pack;
  },
  
  drewCard: function(details) {
  	    	  	   	  
	  var hand = null;
	  if (details.id == util.getMyId()) {
	  	hand = this.hands[0];
	  }
	  else {
	  	for (var i = 1; i < this.hands.length; i++) {
	  		if (this.hands[i].itemId == ('hand_'+details.id)) {
	  			hand = this.hands[i];
	  		}
	  	}
	  }
	  	  	  
	  console.log(details.from);
	  
	  var card = null;
	  if (isDeck(details.from)) {
	  	card = this.decks[0].getTopCard();
	  }
	  else if (isDiscardPile(details.from)) {
	  	card = this.discardpiles[0].getTopCard();
	  }
	  else {
		  return;
	  }
	  	  
	  if (details.id == util.getMyId()) {
	  	card.reveal();
	  }
	  else {
	  	card.hide();
	  }
	  	  	  
	  card.move(hand);
	  	  
	  this.updateStatusDraw(util.getName(details.id), details.from);
	  //card.reveal();
  },
  
  discardedCard: function(details) {
	  var turnIndex = util.getTurnIndex();
	  
	  var hand = this.hands[turnIndex];
	  
	  var card = hand.findCard(details.card);
	  console.log(card.toString());
	  
	  card.move(this.discardpiles[0]);
	  
	  card.reveal();
  },
  
  splashOnly: function() {
  	return false
  },
  
  updateStatusTurn: function() {
	  var s = 'It is '+util.getTurnName() + '\'s turn';
	  this.win.updateStatus(s);
  },
  
  updateStatusDraw: function(name, pile) {
	  if (isDiscardPile(pile)) {
		  pile = 'Discard Pile';
	  }
	  else if (isDeck(pile)) {
		  pile = 'Deck';
	  }
	  var s = name + ' has drawn a card from the ' + pile;
	  this.win.updateStatus(s);
  },
  
  getNumberOfHandsPerPerson: function() {
	  return 1;
  },
  
  getNumberOfDrawPiles: function() {
	  return 1;
  },
  
  getNumberOfDiscardPiles: function() {
	  return 1;
  },
  
  getAddHandComp: function() {
	  return [];
  }
  
};